package model

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

type AccessLog struct {
	gorm.Model
	StatusCode  int    `gorm:"column:status_code"`
	LatencyTime int    `gorm:"column:latency_time"`
	Address     string `gorm:"column:address"`
	Method      string `gorm:"column:method"`
	Path        string `gorm:"column:path"`
}

type AccessPair struct {
	Name  string
	Count int
}

func AddAccessLog(data *AccessLog) error {
	return db.Create(data).Error
}

func PostAccess() ([]AccessPair, error) {
	result := []AccessPair{}
	sql := "SELECT path as Name, count(1) as Count FROM `access_logs` where path like '/post/%' group by path  order by Count desc limit 10;"
	rows, err := db.Raw(sql).Rows()
	if err != nil {
		return result, err
	}

	const Prefix = "/post/"
	const PrefixLen = len(Prefix)
	var name string
	var count int
	for rows.Next() {
		if err := rows.Scan(&name, &count); err == nil {
			if len(name) > PrefixLen {
				id := name[PrefixLen:]
				if post, err := GetLessPostById(id); err == nil {
					result = append(result, AccessPair{
						Name:  post.Title,
						Count: count,
					})
				}
			}
		}
	}
	return result, nil
}

func HourCount(date string) ([]AccessPair, error) {
	result := []AccessPair{}
	sql := fmt.Sprintf(`SELECT HOUR(e.created_at) as Name,count(*) as Count 
	FROM access_logs e 
	WHERE DATE(e.created_at) = '%s' 
	GROUP BY HOUR(e.created_at) ORDER BY Hour(e.created_at);`, date)
	rows, err := db.Raw(sql).Rows()
	if err != nil {
		return result, err
	}

	var name string
	var count int
	for rows.Next() {
		if err := rows.Scan(&name, &count); err == nil {
			result = append(result, AccessPair{
				Name:  name,
				Count: count,
			})
		}
	}
	return result, nil
}
